<?php


namespace SidToken\Crontab;

use SidToken\Model\QueueModel;
use SidToken\Model\SidMinerProductionLogModel;
use SidToken\Model\SidTransferLogModel;
use SidToken\Model\SidTrxErrModel;
use SidToken\Model\SidUserMinerModel;
use SidToken\Utils\MiningUtil;
use SidToken\Utils\TrxRpc;
use TaskCenter\Model\QueueLogModel;
use Ucenter\Model\ScoreModel;

/**
 * 矿机挖矿计划任务
 * Class MiningCrontab
 * @package SidToken\Crontab
 */
class MiningCrontab
{
    const QUEUE_LENGTH = 30;//挖矿每次处理数量

    public function startMining($time)
    {
        redis("mining_status", 'wait');
        redis("mining_page", 1);
        redis("mining_time", $time);

        //关掉过期的矿机
        $UserMinerModel = new SidUserMinerModel();
        $now = strtotime(date("Ymd"));
        $UserMinerModel->where("end_time<" . $now . " AND status=1")->setField('status', $UserMinerModel::STATUS_OFF);
        return [
            'mining_status' => redis("mining_status"),
            'mining_page' => redis("mining_page"),
            'mining_time' => redis("mining_time")
        ];
    }

    public function queryStatus()
    {
        return [
            'status' => redis("mining_status") != null ? redis("mining_status") : "finish",
            'page' => redis("mining_page"),
            'time' => redis("mining_time"),
        ];
    }

    public function mining($r = self::QUEUE_LENGTH)
    {
        $status = redis("mining_status");
        $page = redis("mining_page");
        $page = !$page ? 1 : $page;
        $time = redis("mining_time");

        if (!$time) {
            $mining = [
                'page' => $page,
                'status' => 'wait',
                'lists' => [],
                'error' => 'set time please'
            ];
            return $mining;
        }


        if (($status && $status == 'loading') || ($status && $status == 'finish')) {
            $mining = [
                'page' => $page,
                'status' => $status,
                'lists' => []
            ];
            return $mining;
        }
        //进程锁
        $status = "loading";
        redis("mining_status", $status);

        $UserMinerModel = new SidUserMinerModel();
        $MiningUtil = new MiningUtil();

        /*
         * 矿机配置
         */
        $lists = $UserMinerModel->where("status=1 AND start_time<={$time} AND end_time>={$time}")->page($page, $r)->order("id ASC")->select();
        //TODO 处理矿机
        foreach ($lists as $val) {
            $MiningUtil->mining($val, $time);
        }

        if ($lists == null) {
            $status = 'finish';
        } else {
            $status = 'wait';
            $page++;
        }


        redis("mining_status", $status);
        redis("mining_page", $page);

        $mining = [
            'page' => $page,
            'status' => $status,
            'lists' => $lists
        ];
        return $mining;
    }


//    public function mining()
//    {
//        $UserMinerModel = new SidUserMinerModel();
//        $MinerProductionLogModel = new SidMinerProductionLogModel();
//
//        $time = time();
//        $lists = $UserMinerModel->where("status=1 AND start_time<{$time} AND end_time>{$time}")->order("id ASC")->select();
//
//        $Score = new ScoreModel();
//        foreach ($lists as $val) {
//            $mo = M();
//            $mo->execute('set autocommit=0');
//            $mo->execute('lock tables ocenter_member write , ocenter_coinstore_order write, ocenter_score_log write, ocenter_coinstore_releaselog write');
//            $uid = $val['uid'];
//            $tokenLocked = $mo->table("ocenter_member")->where("uid={$uid}")->getField("score3");
//
//
//            $coinstoreOrderData = array();
//            $coinstoreOrderId = $val['id'];
//            $coinstoreOrderData['left_release_day'] = $val['left_release_day'] - 1;
//            if ($coinstoreOrderData['left_release_day'] <= 0) {
//                $coinstoreOrderData['status'] = 2;
//            }
//            $rs[] = $mo->table("ocenter_coinstore_order")->where("id={$coinstoreOrderId}")->save($coinstoreOrderData);
//
//            $releaseAmount = $val['release_perday'];
//
//            if ($tokenLocked <= $releaseAmount) {
//                $releaseAmount = $tokenLocked;//若不够释放，则全部释放完，避免释放后余额为负数
//            }
//            $coinstoreReleaselog = array(
//                'uid' => $uid,
//                'ctime' => time(),
//                'release_amount' => $releaseAmount,
//                'status' => 1
//            );
//
//            $rs[] = $logid = $mo->table("ocenter_coinstore_releaselog")->add($coinstoreReleaselog);
//
//            $rs = $Score->setUserScoreTransaction($rs, $mo, $uid, $releaseAmount, 3, 'dec', 'CoinstoreReleaselog', $logid, '每日释放A积分');
//            $rs = $Score->setUserScoreTransaction($rs, $mo, $uid, $releaseAmount, 1, 'inc', 'CoinstoreReleaselog', $logid, '每日释放A积分');
//            if (check_arr($rs)) {
//                $mo->execute('commit');
//                $mo->execute('unlock tables');
//            } else {
//                $mo->execute('rollback');
//            }
//
//        }
//    }
}